package com.numone.testble;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.numone.testble.ble.BleConnectPresenter;
import com.numone.testble.ble.BleEntity;
import com.numone.testble.ble.BleHelper;
import com.numone.testble.ble.BleScanPresenter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private List<BleEntity> bleList = new ArrayList<>();
    private Activity activity;
    private BleAdapter bleAdapter;

    private BleHelper bleHelper;
    private SwipeRefreshLayout refreshLayout;

    private String TAG = "TestBle";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activity = this;

        bleAdapter = new BleAdapter();
        refreshLayout = (SwipeRefreshLayout)findViewById(R.id.srl);
        recyclerView = (RecyclerView)findViewById(R.id.rv_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(bleAdapter);

        initBleHelper();

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                bleList.clear();
                bleAdapter.notifyDataSetChanged();
                bleHelper.scanBle();
            }
        });

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.BLUETOOTH,Manifest.permission.BLUETOOTH_ADMIN};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, 111);
        }
    }

    @Override
    public void onResume(){
        super.onResume();
        if(null !=bleHelper){
            bleHelper.getConnectedBle();
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if(null != bleHelper){
            bleHelper.disconnectAllDevice();
            bleHelper.release();
        }
    }

    private void initBleHelper(){
        bleHelper = new BleHelper();
        bleHelper.setOnBleScanCallback(new BleScanPresenter.OnBleScanCallback() {
            @Override
            public void onScanStarted() {
                Log.e(TAG,"onScanStarted");
            }

            @Override
            public void onScanning(BluetoothDevice bleDevice, int rssi) {
                Log.e(TAG,"onScanning="+bleDevice.getName());
            }

            @Override
            public void onScanFinished(List<BleEntity> list) {
                int size = 0;
                if(null != list){
                    size = list.size();
                    bleList.addAll(list);
                }
                Log.e(TAG,"onScanFinished size="+size);
                bleAdapter.notifyDataSetChanged();
                refreshLayout.setRefreshing(false);
            }
        });

        bleHelper.setOnConnectCallBack(new BleConnectPresenter.OnConnectCallBack() {
            @Override
            public void onStartConnect(BluetoothDevice bleDevice) {
                Log.e(TAG,"onStartConnect="+bleDevice.getName());
            }

            @Override
            public void onConnectFail(BluetoothDevice bleDevice, Exception e) {
                String error = e==null?"null":e.toString();
                Log.e(TAG,"onConnectFail Exception="+error);
                bleAdapter.notifyDataSetChanged();
            }

            @Override
            public void onConnectSuccess(BluetoothDevice bleDevice) {
                Log.e(TAG,"onConnectSuccess bleDevice="+bleDevice.getName());
                bleAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDisConnected(BluetoothDevice bleDevice) {
                Log.e(TAG,"onDisConnected bleDevice="+bleDevice);
                bleAdapter.notifyDataSetChanged();
            }
        });
    }

    private class BleAdapter extends RecyclerView.Adapter<ViewHolder> {

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(activity).inflate(R.layout.item_ble, parent, false);
            ViewHolder holder = new ViewHolder(activity, itemView, parent);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            BleEntity entity = bleList.get(position);
            String tv = entity.getName()+"\n"
                    +entity.getMac()+"\n"
                    +entity.getRssi();
            holder.<TextView>getView(R.id.tv).setText(tv);

            holder.getView(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bleHelper.connectBle(entity.getMac());
                }
            });
            holder.getView(R.id.btn_disconnect).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bleHelper.disconnectAllDevice();
                }
            });

            BluetoothDevice device = bleHelper.getConnectedBle();
            if(null != device && device.getAddress().equals(entity.getMac())){
                holder.getView(R.id.btn_connect).setVisibility(View.GONE);
                holder.getView(R.id.btn_disconnect).setVisibility(View.VISIBLE);
            }else {
                holder.getView(R.id.btn_connect).setVisibility(View.VISIBLE);
                holder.getView(R.id.btn_disconnect).setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return bleList.size();
        }
    };

    public class ViewHolder extends RecyclerView.ViewHolder {
        private SparseArray<View> mViews;
        private View mConvertView;
        private Context mContext;

        public ViewHolder(Context context, View itemView, ViewGroup parent)
        {
            super(itemView);
            mContext = context;
            mConvertView = itemView;
            mViews = new SparseArray<>();
        }

        /**
         * 通过viewId获取控件
         *
         * @param viewId
         * @return
         */
        public <T extends View> T getView(int viewId)
        {
            View view = mViews.get(viewId);
            if (view == null)
            {
                view = mConvertView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return (T) view;
        }
    }
}